$(document).ready(
function() {
	CloakManager = new _CloakManager();
    Core = new _Core();
    Core.Init();
    $("div.scrollable").scrollable({ size: 1 }).mousewheel();
}
);

var Core = null;
var ClientCommandsManager = null;
var ConstantsManager = null;
var NavigationManager = null;
var CloakManager = null;
var AuthManager = null;

_Core = function() {
    this.CoreBlocks = [];
}

_Core.prototype = {
    Init: function() {
        ClientCommandsManager = new _ClientCommandsBlock();
        ConstantsManager = new _ConstantsBlock();
        NavigationManager = new _NavigationBlock();
        AuthManager = new _AuthBlock();

        Core.CoreBlocks.push(ClientCommandsManager);
        Core.CoreBlocks.push(ConstantsManager);
        Core.CoreBlocks.push(AuthManager);
        Core.CoreBlocks.push(NavigationManager);
     
        ClientCommandsManager.Init();
        ConstantsManager.Init();
        AuthManager.Init();
        NavigationManager.Init();
    },
    BlockInitCompleteSuccess: function() {
        this.InitCompleted();
    },
    InitCompleted: function() {
        var result = false;
        for (var key in Core.CoreBlocks) {
            result = Core.CoreBlocks[key].IsInit;
        }
        if (result) {
            proc = new Process();
            proc.Go();
        }
    }
}
//*******************************************Cloak Manager Block*************************************************
_CloakManager = function() {
    this.State = true;
}
_CloakManager.prototype = {
    Switch: function() {
        if (this.State) {
            this.OffCloak();
        } else {
            this.OnCloak();
        }
    },
    HideLayout: function(){
    	$("body").css("visibility", "hidden")
    },
    ShowLayout: function(){
    	$("body").css("visibility", "visible")
    },
    OnCloak: function(hideLayout, showLoading){
    	if(hideLayout){
    		this.HideLayout();
    	}
    	if(showLoading){
            $(".Loading").show();
    	}
    	$(".Cloak").show();
        this.State = true;
    },
    OffCloak: function(showLayout, hideLoading){
    	if(showLayout){
    		this.ShowLayout();
    	}
    	if(hideLoading){
            $(".Loading").hide();
    	}
    	$(".Cloak").hide();
        this.State = false;
    }
}
//*******************************************Client Commands Block*************************************************
_ClientCommandsBlock = function() {
    //Clientcommand list
    this.Commands = null;
    this.IsInit = false;
}
_ClientCommandsBlock.prototype = {

    //**************Init block. This block initialize client command list********************* 
    Init: function() {
        var init = {};
        init.CommandName = "InitialiseClientCommands";
        init.ExecuteMethod = "ServerOnly";
        this.Execute(init, this.InitSuccessHandler, this.InitErrorHandler, false, null);
    },

    InitSuccessHandler: function(data, status, request) {
    	ClientCommandsManager.Commands = data;
    	ClientCommandsManager.IsInit = true;
        Core.BlockInitCompleteSuccess();
    },

    InitErrorHandler: function(request, status, errortrow) {
        ClientCommandsManager.IsInit = false;
    },
    //***************************************************************************************

    //Find client command by name and present it
    Get: function(name) {
        for (var i in this.Commands) {
            if (i == name) {
                return this.Commands[i];
            }
        }
    },

    //Execute client command
    Execute: function(commandObj, sHandler, eHandler, isAsync, url) {
        if (typeof (isAsync) == "undefined") {
            isAsync = true;
        }
        if (!sHandler) {
            sHandler = this.DefaultSuccessHandler;
        }

        if (!eHandler) {
            eHandler = this.DefaultErrorHandler
        }

        if (!url) {
            url = "CommonHandler"
        }

        switch (commandObj.ExecuteMethod) {
            case "ClientOnly": //ClientOnly
                eval(commandObj.ClientFunctionReference);
                break;
            case "ClientAndServer":
                break;
            case "ServerOnly": //ServerOnly
                $.ajax({
                    async: isAsync,
                    type: "GET",
                    url: url,
                    cache: false,
                    data: ({ commandName: commandObj.CommandName, command: this.ParseObjToString(commandObj) }),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    success: sHandler,
                    error: eHandler
                });
                break;
        }
    },

    ParseObjToString: function(obj) {
        var result = "";

        if (obj && obj != "") {
            result += "{";

            for (var key in obj) {
                result = result + "\"" + key + "\":\"" + obj[key] + "\",";
            }

            result = result.substring(0, result.length - 1);

            result += "}";
        }

        return result;
    },

    //Default success handler
    DefaultSuccessHandler: function(data, status, request) {
    },

    //Deafault error handler
    DefaultErrorHandler: function(request, status, errortrow) {
    	 alert('ERROR ' + errortrow);
    }
}
//*******************************************Navigation Block*************************************************
_NavigationBlock = function() {
    this.Stack = [];
    this.IsInit = false;
    this.CurrentTarget = null;
    this.GrantedPages = ["auth", "reg"];
}

_NavigationBlock.prototype = {
    Init: function(){
    	this.CurrentTarget = $.query_param("target");
    	this.IsInit = true;
        Core.BlockInitCompleteSuccess();
    },
    GetCurrentTarget: function(){
    	return this.CurrentTarget;
    },
    GoTo: function(to) {
    	if(this.PageIsGrantedForAnonymusNavigation(to) || AuthManager.Identify())
    		window.location.search = "?" + "target=" + to;  
    },
    PageIsGrantedForAnonymusNavigation: function(page){
    	for(var i=0,ic=this.GrantedPages.length; i<ic; i++){
    		if(page==this.GrantedPages[i]){
    			return true;
    		}
    	}
    	return false;
    }
}
//*******************************************Auth Block*************************************************
_AuthBlock = function() {
    this.IsInit = false;
}

_AuthBlock.prototype = {
    Init: function(){
    	AuthManager.IsInit = true;
        Core.BlockInitCompleteSuccess();
    },
    Identify: function() { 
    	var sId = $.cookie("sessionId");
        if(sId){ 
            CloakManager.OffCloak(true,true);
        }
    	return sId != null; 
    }
}
//*******************************************Client Constants Block*************************************************
_ConstantsBlock = function() {
    this.Constants = null;
    this.IsInit = false;
}
_ConstantsBlock.prototype =
{
    Init: function() {
        var _InitialiseClientConstants = ClientCommandsManager.Get("InitialiseClientConstants");
        ClientCommandsManager.Execute(_InitialiseClientConstants, this.SuccessHandler, this.ErrorHandler, false, null); 
    },
    
    SuccessHandler: function(data, status, request) {
    	ConstantsManager.Constants = data;
    	ConstantsManager.IsInit = true;
        Core.BlockInitCompleteSuccess();
    },

    ErrorHandler: function(request, status, errortrow) {
    	ConstantsManager.IsInit = false;
    },
    //Find const by name and present it
    Get: function(name) {
        for (var i in this.Constants) {
            if (i == name) {
                return this.Constants[i];
            }
        }
    }
}  